from sys import exc_info
import cv2, numpy as np
from time import sleep
from findimage import find_template
from wins import reSize, bkg_click, dxcamCap as loc_capture #screezeCap or dxcamCap 二选一

WIDTH_WIN = 832
delta_X = 5
delta_Y	= 29
scaR = WIDTH_WIN/865
HEIGHT_WIN = int(0.5625*WIDTH_WIN)

coords_spec={"map":(0.876,0.111), "close_map":(0.118,0.109), "checkin":[0.52, 0.803], "off":(0.98,0.037)}
mapPanl = cv2.resize(cv2.imread('./Pics/MapPanl.png'), None, fx=WIDTH_WIN/1362, fy=WIDTH_WIN/1362, interpolation=cv2.INTER_AREA)
Y_list = list(range(int(19*scaR), int(950*scaR), int(32.5*scaR)))
map_cls = {'vip':0, 'yivi1':[11, 1], 'uamo1':[7, 1], 'byud1':[12, 1], 'anny':13, 'godu':20, 'ufyr':23, 'moyr':27, 'yihw':28}
def map_switch(hWnd, amap, level = 1):
	if amap != 'ugyu':
		map_y = Y_list[map_cls[amap][0]] if type(map_cls[amap]) is list else Y_list[map_cls[amap]]
		n = 6; dis = HEIGHT_WIN
		while (n:=n-1) > 0:
			image = loc_capture(hWnd)[int(0.163*HEIGHT_WIN + delta_Y):int(0.725*HEIGHT_WIN + delta_Y), int(0.11*WIDTH_WIN + delta_X):int(0.216*WIDTH_WIN + delta_X)]
			cv2.imwrite(f'capturePart{n}.png', image)
			match_result = find_template(mapPanl, image)
			if match_result is None:
				#bkg_click(hWnd, coords_spec["map"]) # 打开地图
				print('None')
				continue
			else:
				dis = int(match_result['result'][1]) - map_y
				print(n, match_result['result'][1], dis, round(abs(dis)/HEIGHT_WIN, 3))
				if abs(dis)/HEIGHT_WIN > 0.9:
					dragDelta = int(0.139*HEIGHT_WIN) if dis > 0 else int(-0.139*HEIGHT_WIN)
				else:
					dragDelta = int(0.12*HEIGHT_WIN) if dis > 0 else int(-0.12*HEIGHT_WIN)
				if abs(dis) > 0.25 * HEIGHT_WIN:
					bkg_click(hWnd, (0.192, 0.445), True, dragDelta); sleep(2)
				else:
					break
		bkg_click(hWnd, (0.192, 0.445 - dis/HEIGHT_WIN)); sleep(0.5)
		if type(map_cls[amap]) is list:
			bkg_click(hWnd, (0.192,0.445 + (0.05 * map_cls[amap][1]) - dis/HEIGHT_WIN)); sleep(0.5)
		if amap == 'vip':
			sleep(9)
			bkg_click(hWnd, coords_spec["checkin"])
	else:
		map_switch(hWnd, 'godu')
		bkg_click(hWnd, coords_spec["map"]) # 打开地图
		bkg_click(hWnd, (0.8785, 0.712), True, -200); sleep(0.5) # 放大
		bkg_click(hWnd, (0.575,0.51))
		bkg_click(hWnd, coords_spec["close_map"]) # 关闭地图
		sleep(3)
		bkg_click(hWnd, (0.665,0.41)) # 圣域传送员
		sleep(1)
		bkg_click(hWnd, (0.376,0.32+0.064*(level-2))) # 圣域2, 等差0.064
		sleep(0.5)
		bkg_click(hWnd, (0.521,0.805)) # 进入
	sleep(1)
	
if __name__ == "__main__":
	from sys import argv
	if len(argv) > 2:
		reSize(delta_X, delta_Y, WIDTH_WIN, hwnd = argv[-2])
		map_switch(argv[-2], argv[-1])